package com.atguigu.srb.core.controller.api;


import com.atguigu.guigu.common.result.R;
import com.atguigu.service.base.utils.JwtUtils;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.entity.vo.UserIndexVO;
import com.atguigu.srb.core.pojo.entity.vo.UserInfoVo;
import com.atguigu.srb.core.pojo.entity.vo.UserRegisterVO;
import com.atguigu.srb.core.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author Atguigu
 * @since 2022-11-19
 */
@RestController

@RequestMapping("/api/core/userInfo")
public class ApiUserInfoController {
    @Resource
    UserInfoService userInfoService;
    @ApiOperation("用户中心首页数据查询")
    @GetMapping("auth/getUserIndex")
    public R getUserIndex(@RequestHeader(value = "token",required = false)
                                      String token){
        UserIndexVO userIndexVO = userInfoService.getUserIndex(token);
        return R.ok().data("item",userIndexVO);
    }

    @ApiOperation("判断注册手机号是否被占用")
    @GetMapping("isRegist/{mobile}")
    public R isRegist(@PathVariable("mobile") String mobile){
        int count = userInfoService.count(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getMobile, mobile));
        return R.ok().data("flag" , count==0);//true表示可用
    }
    //
    @ApiOperation("登录后查询用户回显数据")
    @GetMapping("auth/getUserInfo")//auth表示当前接口必须登录后才可以访问
    public R getUserInfo(@RequestHeader(value = "token",required = false)
                                     String token){//获取token参数
        //请求头传token：  token     token字符串
        Long userId = JwtUtils.getUserId(token);
        //userId nickname  头像
        UserInfo userInfo = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo , userInfoVo);
        return R.ok().data("item",userInfoVo);
    }
    @ApiOperation("登录")
    @PostMapping("login")
    public R login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        //单点登录 使用的是token模式，只要返回token   格式为jwt
        String token = userInfoService.login(userInfo,request);
        return R.ok().data("token" , token);
    }

    //自定义vo类接收前端提交的表单数据
    @ApiOperation("注册")
    @PostMapping("register")
    public R register(@RequestBody UserRegisterVO userRegisterVO){
        userInfoService.register(userRegisterVO);
        return R.ok().message("注册成功");
    }
}

